package com.test.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * description:
 * 后置处理器的使用
 * 首先需要实现BeanPostProcessor
 *
 * 不是针对某个bean，对所有的bean生效
 *
 * @author 颜真明
 * @date 2023/4/28  17:23
 */
@Component("beanPostProcessorExtend")
public class BeanPostProcessorExtend implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (beanName.equals("userService")) {
            System.out.println("-------初始化前--------");
            System.out.println("执行postProcessBeforeInitialization");
            ((UserServiceImpl)bean).setBeanPostProcessorTest("验证后置处理器是否赋值成功");
        }

        return bean;
    }


    /**
     * aop是在这一步完成的
     *
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (beanName.equals("userService")) {
            System.out.println("-------初始化后--------");
            System.out.println("执行postProcessAfterInitialization");

            Object proxyInstance = Proxy.newProxyInstance(BeanPostProcessorExtend.class.getClassLoader()
                    , bean.getClass().getInterfaces(), new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("-----aop-----");
                            System.out.println("执行代理逻辑");
                            return method.invoke(bean, args);
                        }
                    });

            // 这里返回代理对象
            return proxyInstance;

        }
        return bean;
    }

}
